/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.pig4cloud.pigx.contract.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.enums.CommonDictEnum;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.contract.bo.ContractStatisticsBO;
import com.pig4cloud.pigx.contract.entity.ContractTrade;
import com.pig4cloud.pigx.contract.mapper.ContractTradeMapper;
import com.pig4cloud.pigx.contract.service.ContractTradeService;
import com.pig4cloud.pigx.contract.utils.ContractUtils;
import com.pig4cloud.pigx.contract.vo.ContractTradeHistoryByPositionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import com.pig4cloud.pigx.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 成交记录表
 *
 * @date 2022-08-11 10:08:52
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/contracttrade" )
@Api(value = "contracttrade", tags = "成交记录表管理")
public class ContractTradeController {

    private final  ContractTradeService contractTradeService;

    private final ContractUtils utils;

    /**
     * 分页查询
     * @param page 分页对象
     * @param contractTrade 成交记录表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_view','agent_view')" )
    public R getContractTradePage(Page<ContractTrade> page, ContractTrade contractTrade) {
		QueryWrapper<ContractTrade> query = new QueryWrapper<>();
		query.eq("is_robot","0");
		// 时间检索
		if (contractTrade.getCreateTime() != null) {
    		String time = contractTrade.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			query.like("create_time",time);
		}
		if (contractTrade.getSymbolId() != null) {
			query.eq("symbol_id",contractTrade.getSymbolId());
		}
		if (contractTrade.getOrderId() != null) {
			query.eq("order_id",contractTrade.getOrderId());
		}
		if (contractTrade.getId() != null) {
			query.like("id",contractTrade.getId());
		}
		if (contractTrade.getUserId() != null) {
			query.like("user_id",contractTrade.getUserId());
		}
		query.orderByDesc("create_time");
		Page<ContractTrade> res = contractTradeService.page(page, query);
		res.getRecords().forEach(e -> {
			utils.setScaleBySymbol(e,e.getSymbolName());
		});
		ContractTrade one = contractTradeService.getBaseMapper().selectOne(
				query.select("sum(num) 'num'", "sum(price) 'price'", "sum(handling_fee) 'handlingFee'")
		);
		// 带有统计数据进行模型拼装
		ContractStatisticsBO<ContractTrade> bo = new ContractStatisticsBO<>();
		bo.setPage(res);
		bo.setStatistics(one);
		return R.ok(bo);
    }


    /**
     * 通过id查询成交记录表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(contractTradeService.getById(id));
    }

    /**
     * 新增成交记录表
     * @param contractTrade 成交记录表
     * @return R
     */
    @ApiOperation(value = "新增成交记录表", notes = "新增成交记录表")
    @SysLog("新增成交记录表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_add')" )
    public R save(@RequestBody ContractTrade contractTrade) {
        return R.ok(contractTradeService.save(contractTrade));
    }

    /**
     * 修改成交记录表
     * @param contractTrade 成交记录表
     * @return R
     */
    @ApiOperation(value = "修改成交记录表", notes = "修改成交记录表")
    @SysLog("修改成交记录表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_edit')" )
    public R updateById(@RequestBody ContractTrade contractTrade) {
        return R.ok(contractTradeService.updateById(contractTrade));
    }

    /**
     * 通过id删除成交记录表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除成交记录表", notes = "通过id删除成交记录表")
    @SysLog("通过id删除成交记录表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(contractTradeService.removeById(id));
    }


    /**
     * 导出excel 表格
     * @param contractTrade 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('contract_contracttrade_export')" )
    public List<ContractTrade> export(ContractTrade contractTrade) {
        return contractTradeService.list(Wrappers.query(contractTrade));
    }

	/**
	 * 获取总交易量
	 * @return
	 */
	@ApiOperation(value = "获取总交易量", notes = "获取总交易量")
	@GetMapping("/transaction/sum")
	@PreAuthorize("@pms.hasPermission('contract_contracttrade_view')" )
	public R getFinance() {
		BaseMapper<ContractTrade> mapper = contractTradeService.getBaseMapper();
		ContractTrade trade = mapper.selectOne(new QueryWrapper<ContractTrade>() {{
			select("sum (trade_value) 'tradeValue'");
			eq("is_robot", CommonDictEnum.YesOrNo.NO.getValue());
		}});
		trade.setTradeValue(trade.getTradeValue().setScale(3, RoundingMode.HALF_UP));;
		return R.ok(trade);
	}

	/**
	 * 根据仓位id获取订单详情
	 * @return
	 */
	@ApiOperation(value = "根据仓位id获取手续费", notes = "根据仓位id获取手续费")
	@GetMapping("/position/{id}" )
	@PreAuthorize("@pms.hasPermission('contract_contracttrade_view')" )
	public R getServiceCharge(@PathVariable Long id) {
		BaseMapper<ContractTrade> mapper = contractTradeService.getBaseMapper();
		List<ContractTrade> trades = mapper.selectList(new QueryWrapper<ContractTrade>() {{
			eq("position_id", id);
			select("create_time,order_type,side,trade_value,handling_fee,price");
		}});
		return R.ok(trades);
	}

	/**
	 * 根据仓位id获取开仓交易记录
	 * @return 1
	 */
	@GetMapping("/position/trade/{id}")
	public R<List<ContractTradeHistoryByPositionVO>> getTradeHistoryByPosition(@PathVariable("id") Long id) {
		BaseMapper<ContractTrade> mapper = contractTradeService.getBaseMapper();
		List<ContractTrade> list = mapper.selectList(new QueryWrapper<ContractTrade>() {{
			eq("position_id", id);
			eq("operation_type", "0");
			select("create_time",
					"price",
					"side",
					"num",
					"handling_fee",
					"order_type",
					"trade_value",
					"symbol_name"
			);
		}});
		List<ContractTradeHistoryByPositionVO> voList = new ArrayList<>();
		for (ContractTrade trade : list) {
			ContractTradeHistoryByPositionVO vo = new ContractTradeHistoryByPositionVO();
			BeanUtils.copyProperties(trade,vo);
			utils.setScaleBySymbol(vo,vo.getSymbolName());
			voList.add(vo);
		}
		return R.ok(voList);
	}

}
